package cn.huanzi.qch.springbootmybatis.dingding;

import cn.hutool.core.codec.Base64;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.taobao.api.TaobaoResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * @author keven
 * @date 2023-02-09 11:41 上午
 * @Description
 */

@Component
@ConditionalOnExpression("${notify.dingtalk.enable:false}")
public class DingTalkMessageSender {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkMessageSender.class);

    private DingTalkConfig dingTalkConfig;

    public DingTalkMessageSender(DingTalkConfig dingTalkConfig) {
        this.dingTalkConfig = dingTalkConfig;
    }

    /**
     * 发送文本消息
     * @param msgText 消息内容
     * @return
     */
    public boolean sendTextMessage(String msgText) {
        String logContent = msgText.replace(" ", "").replace("\n", "");
        try {
            logger.info("钉钉群机器人发送Text消息： {}", logContent);
            DingTalkClient client = new DefaultDingTalkClient(getUrl());
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(msgText);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype(DingTalkMessageType.TEXT.getValue());
            request.setText(text);
            TaobaoResponse response = client.execute(request);
            return response.isSuccess();
        } catch (Exception e) {
            logger.error("钉钉群机器人发送Text消息失败 : {} : {}", logContent, e.getLocalizedMessage());
        }
        return false;
    }

    /**
     * 发送Markdown消息
     *
     * @param title   标题
     * @param msgText 消息内容
     * @return
     */
    public boolean sendMarkdownMessage(String title, String msgText) {
        String logContent = msgText.replace(" ", "").replace("\n", "");
        try {
            logger.info("钉钉群机器人发送Markdown消息： {}", logContent);
            DingTalkClient client = new DefaultDingTalkClient(getUrl());
            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
            markdown.setTitle(title);
            markdown.setText(msgText);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype(DingTalkMessageType.MARK_DOWN.getValue());
            request.setMarkdown(markdown);
            TaobaoResponse response = client.execute(request);
            return response.isSuccess();
        } catch (Exception e) {
            logger.error("钉钉群机器人发送Markdown消息失败 : {} : {}", logContent, e.getLocalizedMessage());
        }
        return false;
    }

    /**
     * 获取URL
     *
     * @return
     * @throws Exception
     */
    private String getUrl() throws Exception {
        String accessToken = dingTalkConfig.getAccessToken();
        if (!dingTalkConfig.isEnableSignature()) {
            return String.format(DingTalkConstants.API_SEND_MESSAGE, accessToken);
        } else {
            Long timestamp = System.currentTimeMillis();
            String sign = getSign(timestamp, dingTalkConfig.getSignSecret());
            return String.format(DingTalkConstants.API_SEND_MESSAGE_SIGN, accessToken, timestamp, sign);
        }
    }

    /**
     * 获取签名
     *
     * @param timestamp 时间戳
     * @param secret    钉钉群机器人的签名秘钥
     * @return
     * @throws Exception
     */
    private String getSign(Long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encode(signData)), "UTF-8");
    }

}
